/<template>
  <div class="drawer-container">
    <el-form
      ref="formData"
      :model="formData"
      :disabled="isdisabled"
      :rules="rules"
    >
      <el-form-item
        label="任务名称："
        prop="title"
        label-width="110px"
      >
        <el-input
          v-model="formData.title"
          size="small"
          clearable
          style="width: 100%;height: 32px;"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="小程序："
        prop="mini_app_id"
        label-width="110px"
      >
        <!-- <el-cascader
          v-model="formData.mini_app_id"
          :options="optionsList.miniApp"
          :props="{ expandTrigger: 'hover', emitPath: false }"
          collapse-tags
          clearable
          filterable
          :show-all-levels="false"
          @change="onGameChange"
        >
          <template slot-scope="{ data }">
            <span>{{ data.label }}</span>
          </template>
        </el-cascader> -->
        <el-select
          v-model="formData.mini_app_id"
          clearable
          placeholder="请选择"
          style="width: 100%;height: 32px;"
          size="small"
          @change="onGameChange"
        >
          <el-option
            v-for="item in optionsList.mini_app_id"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            style="display: flex; align-items: center;justify-content: space-between;"
          >
            <span style="float: left">{{ item.name }}</span>
            <svg-icon
              v-if="item.app_type==1"
              style="float: right;"
              icon-class="miniapp"
              class="imageIcon"
            />
            <svg-icon
              v-else
              style="float: right;"
              icon-class="douyin"
              class="imageIcon"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="发送时间："
        prop="send_time"
        label-width="110px"
      >
        <template>
          <div class="formTime">
            <el-radio-group
              v-model="resource"
              @change="resourceChange"
            >
              <el-radio label="1">立即发送</el-radio>
              <el-radio label="2">定时发送</el-radio>
            </el-radio-group>
            <!--  -->
            <div>
              <el-date-picker
                v-if="resource == '2'"
                v-model="formData.send_time"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                size="small"
                placeholder="选择日期时间"
              />
            </div>
            <!-- <BiDatePicker :picker-options="pickerOptions" v-show="resource == '2'" v-model="formData.send_time" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" style="margin-left: 20px" size="mini" type="datetime" placeholder="选择日期时间"></BiDatePicker> -->
          </div>
        </template>
      </el-form-item>
      <el-form-item
        label="选择模板："
        prop="template_id"
        label-width="110px"
      >
        <el-select
          v-model="formData.template_id"
          placeholder="请选择"
          clearable
          style="width: 100%;height: 32px;"
          size="small"
          @change="onGetKeywordForTemplate(formData.template_id)"
        >
          <el-option
            v-for="item in optionsList.templateList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
            :disabled="item.status * 1 === 2"
          > </el-option>
        </el-select>
        <div
          v-if="formData.template_id"
          class="card"
        >
          <div
            class="head-card"
            style="line-height: 20px !important;"
          >模板消息</div>
          <div class="body-card">
            <el-form
              v-if="formData.template_id"
              ref="modelFrom"
              :disabled="isdisabled"
            >
              <el-form-item
                v-for="(item, index) in formModel"
                :key="index"
                :label="item.keyword"
                :prop="'model' + index"
                label-width="100px"
                style="padding: 10px 0;"
                class="item-form-keyword"
              >
                <el-time-picker
                  v-if="item.time"
                  v-model="item.text"
                  placeholder="选择时间"
                  value-format="HH:mm"
                  format="HH:mm"
                  style="width: 100%;height: 32px;"
                  @change="onModelChange"
                > </el-time-picker>
                <!-- <BiDatePicker v-if="item.time" value-format="HH:mm:ss" format="HH:mm:ss" v-model="item.text" type="time" placeholder="选择时间" @change="onModelChange"></BiDatePicker> -->
                <BiDatePicker
                  v-else-if="item.date"
                  v-model="item.text"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%;height: 32px;"
                  @change="onModelChange"
                ></BiDatePicker>
                <BiDatePicker
                  v-else-if="item.datetime"
                  v-model="item.text"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期"
                  style="width: 100%;height: 32px;"
                  @change="onModelChange"
                ></BiDatePicker>
                <el-input
                  v-else
                  v-model="item.text"
                  clearable
                  :placeholder="item.Placeholder"
                  style="width: 100%;height: 32px;"
                  @change="onModelChange"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-form-item>
      <el-form-item
        label="跳转链接："
        prop="mini_app_id"
        label-width="110px"
      >
        <el-cascader
          v-model="formData.playlet_id"
          :disabled="!formData.mini_app_id"
          :options="optionsList.playletList"
          style="width: 100%;"
          size="small"
          @expand-change="handleChange"
        ></el-cascader>
      </el-form-item>
      <div class="button-all">
        <el-button
          v-if="data.code != 2"
          type="button"
          @click="onCancel"
        >取消</el-button>
        <el-button
          type="primary"
          :disabled="false"
          :loading="loading"
          @click="onsubmit('formData')"
        >发布</el-button>

      </div>
    </el-form>
  </div>
</template>

<script>
const id = 0
import { getDateYear } from '@/utils/timeFactory'
import { commonData, miniAppList } from '@/api/common'
import { getMiniTaskDetail, getTemplateList, getKeywordForTemplate, setMiniTaskAdd, updateMiniTask } from '@/api/subscribe'
import { load } from 'jszip/lib/object'
export default {
  name: 'SetSubscribe',
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      id: '',
      resource: '1',
      isdisabled: false,
      app_type: '',
      optionsList: {
        mini_app_id: [],
        mainGameList: [],
        gameList: [],
        templateList: [],
        playletList: []
      },
      formData: {
        mini_app_id: '',
        template_id: '',
        playlet_id: '',
        type: '',
        send_time: ''
      },
      formModel: [],
      modelContent: [],
      rules: {
        weixin_blongs_id: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        mini_app_id: [{ required: true, message: '请选择小游戏', trigger: 'blur' }],
        title: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        template_id: [{ required: true, message: '请选择模板', trigger: 'blur' }],
        send_time: [{ required: true, message: '请选择发送时间', trigger: 'blur' }]
      },
      modelrules: [],
      templatePlaceholder: {
        thing: '20个以内字符',
        number: '32位以内数字',
        letter: '32位以内字母',
        symbol: '5位以内符号',
        character_string: '32位以内数字、字母或符号',
        amount: '1个币种符号+10位以内纯数字，可带小数，结尾可带“元”',
        phone_number: '17位以内，数字、符号',
        car_number: '8位以内，第一位与最后一位可为汉字，其余为字母或数字',
        name: '10个以内纯汉字或20个以内纯字母或符号',
        phrase: '5个以内汉字',
        enum: '只能上传枚举值范围内的字段值'
      }
    }
  },
  async mounted() {
    console.log(this.data)
    this.id = this.data.id
    this.app_type = this.data.app_type ? this.data.app_type : ''
    this.searchAsync('miniApp')
    this.getMiniAppList()
    // code == 1 编辑 code == 2 查看 code == 3 添加
    if (this.data.code === 1) {
      await this.onGetMiniTaskTemplateList(this.data.mini_app_id)
      await this.onGetKeywordForTemplate({ template_id: this.data.template_id })
      await this.onGetCataDetail(this.id)
    } else if (this.data.code === 2) {
      await this.onGetMiniTaskTemplateList(this.data.mini_app_id)
      await this.onGetKeywordForTemplate({ template_id: this.data.template_id })
      await this.onGetCataDetail(this.id)
      this.isdisabled = true
    }
  },
  methods: {
    async getMiniAppList() {
      const res = await miniAppList()
      if (res.status_code === 1) {
        this.optionsList.mini_app_id = res.data
      }
    },
    resourceChange(value) {
      if (value == 1) {
        // const date = getDateYear(new Date())
        // this.$set(this.formData, 'send_time', date)
        // console.log(this.formData)
        // this.$forceUpdate()
        this.$refs['formData'].clearValidate(['send_time'])
      }
    },
    // 获取剧集列表
    async onGetPlayletList() {
      const res = await commonData({
        type: 'miniAppPlaylet',
        mini_app_id: this.formData.mini_app_id
      })
      if (res.status_code === 1) {
        this.optionsList.playletList = res.data.data.map((item, index) => {
          return {
            ...item,
            children: []
          }
        })
      }
    },
    handleChange(value, index) {
      const id = value[0]
      commonData({ type: 'chapterDrop', value: id }).then((res) => {
        if (res.status_code === 1) {
          const children = res.data.data
          this.optionsList.playletList.forEach((item, index) => {
            if (item.value == id) {
              this.optionsList.playletList[index].children = children
            }
          })
        }
      })
    },
    async searchAsync(type, value) {
      const page = {
        page_size: 200,
        page: 1
      }
      // this.selectLoading = true
      const params = { type, value, ...page }

      const res = await commonData(params)
      // this.selectLoading = false
      if (res.status_code === 1) {
        this.optionsList[type] = res.data.data
      }
    },
    async onGetCataDetail(id) {
      const params = {
        id
      }
      const res = await getMiniTaskDetail(params)
      if (res.status_code === 1) {
        this.formData = res.data.data
        this.formData.mini_app_id = res.data.data.mini_app_id
        this.resource = res.data.data.type
        const arr = JSON.parse(res.data.data.content).keywords
        console.log(this.formModel)
        this.formModel.forEach((it, i) => {
          arr.forEach((item) => {
            if (this.app_type == 1 && it.value == item.value) {
              this.$set(this.formModel[i], 'text', item.content)
            }
            if (this.app_type == 2 && it.keyword == item.keyword) {
              this.$set(this.formModel[i], 'text', item.content)
            }
          })
        })
        await this.onGetPlayletList()
        this.formData.playlet_id = []
        const playlet_id = res.data.data.link.split('?')[1].split('&')[0].split('=')[1]
        const chapter_id = res.data.data.link.split('?')[1].split('&')[1].split('=')[1]
        const cascader = [playlet_id * 1, chapter_id * 1]
        await this.handleChange(cascader)
        this.formData.playlet_id = cascader
      }
    },
    async onGetMiniTaskTemplateList(id) {
      if (id) {
        const params = {
          mini_app_id: id
        }
        const res = await getTemplateList(params)
        if (res.status_code === 1) {
          this.optionsList.templateList = res.data.data
        }
      } else {
        this.optionsList.templateList = []
      }
    },
    onsubmit() {
      let flag = false
      this.formModel.forEach((item, i) => {
        if (!item.text) {
          flag = true
        }
      })
      if (flag) {
        this.$message.warning('请将信息输入完整')
        return
      }
      if (this.formData.title && this.formData.mini_app_id && this.formData.template_id && this.resource) {
        if (this.data.code === 1) {
          // 编辑
          this.onUpdateMiniTask()
        } else if (this.data.code === 2) {
          this.onCancel()
        } else {
          // 添加
          this.onSetMiniTaskAdd()
        }
      } else {
        this.$message.warning(`请将信息输入完整`)
      }
    },
    onCancel() {
      this.visible = false
      this.$emit('cancel')
    },
    async onSetMiniTaskAdd() {
      const date = getDateYear(new Date())
      const params = {
        ...this.formData,
        playlet_id: this.formData.playlet_id[0],
        chapter_id: this.formData.playlet_id[1],
        send_time: this.resource * 1 === 1 ? date : this.formData.send_time,
        content: this.modelContent,
        type: this.resource,
        app_type: this.app_type
      }
      this.loading = true
      const res = await setMiniTaskAdd(params)
      if (res.status_code === 1) {
        console.log('123456')
        this.loading = false
        this.$emit('ok')
        this.onCancel()
      }
    },
    async onGetKeywordForTemplate(id) {
      const params = {
        template_id: id
      }
      const res = await getKeywordForTemplate(params)
      if (res.status_code === 1) {
        this.formModel = res.data.data
        this.formModel.forEach((item, i) => {
          if (item.value.indexOf('time') != -1) {
            this.$set(this.formModel[i], 'time', true)
          } else if (item.value.indexOf('date') != -1) {
            this.$set(this.formModel[i], 'date', true)
          } else if (this.app_type == 2 && (item.keyword.indexOf('时间') != -1 || item.keyword.indexOf('日期') != -1)) {
            this.$set(this.formModel[i], 'datetime', true)
          } else {
            for (const key in this.templatePlaceholder) {
              if (item.value.indexOf(key) != -1) {
                this.$set(this.formModel[i], 'Placeholder', this.templatePlaceholder[key])
              }
            }
          }
        })
        console.log(this.formModel, '--------------------')
      }
    },
    onModelChange() {
      this.formModel.forEach((item, i) => {
        this.modelContent[i] = {
          keyword_id: item.id,
          content: item.text
        }
      })
      console.log(this.modelContent)
    },
    onGameChange(e) {
      this.onGetMiniTaskTemplateList(this.formData.mini_app_id)
      this.onGetPlayletList()
      this.formModel = {}
      this.formData.template_id = ''
      this.optionsList.mini_app_id.forEach((item) => {
        if (item.id == e) {
          this.app_type = item.app_type
        }
      })
    },
    async onUpdateMiniTask() {
      const date = getDateYear(new Date())
      // console.log(this.modelContent)
      this.onModelChange()
      const params = {
        id: this.formData.id,
        mini_app_id: this.formData.mini_app_id,
        template_id: this.formData.template_id,
        title: this.formData.title,
        send_time: this.resource * 1 === 1 ? date : this.formData.send_time,
        content: this.modelContent,
        type: this.resource,
        playlet_id: this.formData.playlet_id[0],
        chapter_id: this.formData.playlet_id[1],
        app_type: this.app_type
      }
      this.loading = true
      const res = await updateMiniTask(params)
      if (res.status_code === 1) {
        this.loading = false
        this.$message({
          type: 'success', // success error warning
          message: '修改成功'
        })
        this.$emit('ok')
      }
    }
  }
}
</script>

<style lang="scss" scoped >
.drawer-container {
  padding: 20px !important;
  // position: relative;
  .button-all {
    position: absolute;
    bottom: 20px;
    right: 30px;
  }
}
.modelfrom {
  padding: 18px;
  background-color: #ecf2fe;
  margin-top: 18px;
  ::v-deep .el-form-item__label {
    font-weight: normal;
  }
}
.card {
  width: 100%;
  background-color: #fff;
  border: 1px solid #ebeef5;
  margin-top: 10px;
  .head-card {
    width: 100%;
    border-bottom: 1px solid #ebeef5;
    color: #333;
    font-size: 14px;
    font-weight: 600;
    padding: 10px 20px;
    width: 156rpx;
    height: 120rpx;
    border: 0rpx solid #f1f5fd;
    background-color: #f7f8fa;
  }
  .body-card {
    padding: 10px 20px;
  }
}
.item-form-keyword {
  margin-bottom: 0 !important;
}
</style>

